<template>
	<div class="payment-method-container">
		<div class="content-section">
			<!-- 配送方式 -->
			<div class="section-title flex_between">
				<div class="ml5">配送方式</div>
				<div class="flex_row">
					<div class="add-custom-section">
						<el-button type="text" @click="addCustomPayment" class="add-button">
							<i class="el-icon-plus"></i>
							<span>添加自定义配送方式</span>
						</el-button>
					</div>
					<div class="add-custom-section ml20">
						<el-button type="text" @click="addCustomRoute" class="add-button">
							<i class="el-icon-plus"></i>
							<span>添加自定义路线</span>
						</el-button>
					</div>
				</div>
			</div>
			<div class="payment-methods-card" v-for="(item, paraIndex) in paymentMethods" :key="paraIndex">
				<h2 class="mb5"> {{ item.title }} </h2>
				<div v-for="(method, index) in item.list" :key="index" class="payment-method-item flex_between">
					<div class="payment-methods-cell flex_between">
						<div class="method-info" @click="togglePaymentMethod(index)">
							<el-image class="method-icon"
								:src="`static/icon/setting/${getMethodIcon(method.title)}.svg`"></el-image>
							<div class="method-name">{{ method.title }}</div>
						</div>
						<div class="payment-actions">
							<div class="custom-checkbox" :class="{
								'checkbox-checked': method.status == 1
							}" @click.stop="togglePaymentMethod(paraIndex, index)">
								<i v-if="method.status == 1" class="el-icon-check"></i>
							</div>
						</div>
					</div>
					<div class="action-buttons ml10" v-if="method.type != 1">
						<i class="el-icon-edit edit-btn" @click.stop="editPaymentMethod(method)"></i>
						<el-popconfirm confirm-button-text='确实' cancel-button-text='取消'
							:title="'确定要删除收款方式' + method.title + '吗？'" @confirm="deletePaymentMethod(method)">
							<i slot="reference" class="el-icon-delete delete-btn"></i>
						</el-popconfirm>
					</div>
				</div>
			</div>
		</div>
		<div class="footer-section">
			<el-button type="primary" @click="savePaymentHandle" class="save-button">
				保存设置
			</el-button>
		</div>

		<el-dialog title="配送方式" :visible.sync="dialogVisible" width="30%" :before-close="handleClose" append-to-body
			:modal-append-to-body="false" :z-index="3000" @close="handleClose">
			<el-form :model="editForm" label-width="80px">
				<el-form-item label="名 称">
					<el-input v-model="editForm.title" placeholder="请输入配送方式名称"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="confirmEdit">确定</el-button>
			</span>
		</el-dialog>

		<el-dialog title="自定义路线" :visible.sync="boxVisible" width="30%" top="5vh" :before-close="handleClose"
			append-to-body :modal-append-to-body="false" :z-index="3000" @close="handleClose">
			<div style="max-height: 550px;overflow: auto;">
				<el-form ref="customRouteFormRef" :model="customRouteForm" label-width="80px" :rules="customRouteRule">
					<el-form-item label="名 称" prop="title">
						<el-input v-model="customRouteForm.title" placeholder="请输入自定义路线名称"
							style="width: 100%;"></el-input>
					</el-form-item>
					<el-form-item label="选择区域" prop="dist">
						<div class="object-box">
							<div class="object-item" v-for="(ditem, dIndex) in customRouteForm.dist" :key="dIndex">
								<div class="object-item-name-box">
									<div>区 域：</div>
									<el-cascader size="mini" style="width: 75%;" id="selectPrCtAr"
										v-model="customRouteForm.dist[dIndex].codeArr" :options="optionsPosition"
										:props="propsdata" placeholder="省市区"
										@change="handleChange(dIndex, $event)"></el-cascader>
								</div>
								<div class="object-item-delete-box" @click="deleteDist(dIndex)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object" @click="addDist">
								<el-button type="primary" icon="el-icon-plus" circle :disabled="isDisabled"></el-button>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="添加路线" prop="ads">
						<div class="object-box">
							<div class="object-item" v-for="(adtxt, imIndex) in customRouteForm.ads" :key="imIndex">
								<div class="object-item-name-box">
									<div>路线{{ imIndex + 1 }}：</div>
									<el-input type="text" placeholder="输入路线" size="mini"
										v-model="customRouteForm.ads[imIndex]" style="width: 75%;"></el-input>
								</div>
								<div class="object-item-delete-box" @click="deleteObject(imIndex)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object" @click="addAdtxt">
								<el-button type="primary" icon="el-icon-plus" circle :disabled="isDisabled"></el-button>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="备注">
						<el-input v-model="customRouteForm.txt" placeholder="请输入备注" style="width: 100%;"></el-input>
					</el-form-item>
				</el-form>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="boxVisible = false">取消</el-button>
				<el-button type="primary" @click="confirmCustomRoute">确定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, defineProps, defineEmits, watch, computed } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { List } from 'echarts'
const { proxy } = getCurrentInstance()

// 自定义路线
const customRouteForm = ref({
	ads: [""],
	dist: [
		{
			area: "",
			city: "",
			province: "",
			title: "",
			codeArr: []
		},
	],
	id: "0",
	title: "",
	txt: "",
	type: "3",
	status: "1",

})
const customRouteRule = ref({
	title: [
		{ required: true, message: '请输入自定义路线名称', trigger: 'blur' },
		{ min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
	],
	dist: [
		{ required: true, message: '请选择地区', trigger: 'blur' },
	],
	ads: [
		{ required: true, message: '请选择路线', trigger: 'blur' },
	]
})
const boxVisible = ref(false)
const isDisabled = ref(false)
const optionsPosition = ref([])
const propsdata = ref({
	children: "cityList",
	label: "name",
	value: "code",
	expandTrigger: "hover",
	checkStrictly: true,
})

// 新增编辑配送方式
const confirmCustomRoute = async () => {
	console.log("customRouteForm.value===",customRouteForm.value)
	const valid = await proxy.$refs.customRouteFormRef.validate()
	if (!valid) {
		proxy.$message({
			message: '请完善表单信息',
			type: 'warning'
		})
		return
	}
	let params = {
		...customRouteForm.value,
	}
	let isPass = true
	params.dist.forEach((item, index) => {
		if (!item.title) {
			isPass = false
		}
	})
	if (!isPass) {
		proxy.$message.error('请选择区域')
		return
	}
	let is2Pass = true
	params.ads.forEach((item, index) => {
		if (!item) {
			is2Pass = false
			return
		}
	})
	if (!is2Pass) {
		proxy.$message.error('路线内容不能为空')
		return
	}
	console.log("params===",params)
	try {
		let res = await proxy.$api({ url: config.company_sfee_save, data: params })
		if (res.status == 1) {
			boxVisible.value = false
			getSfeeLs()
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	} catch (error) { }
}

// 添加地区
const addDist = () => {
	customRouteForm.value.dist.push({
		area: "", // 632724
		city: "", // 632700
		province: "", // 630000
		title: "" // 青海省玉树藏族自治州治多县
	})
}
// 删除地区
const deleteDist = (index) => {
	if (customRouteForm.value.dist.length > 1) {
		customRouteForm.value.dist.splice(index, 1)
	} else {
		proxy.$message({
			message: '至少选择一个地区',
			type: 'warning'
		})
	}
}

// 添加路线
const addAdtxt = () => {
	customRouteForm.value.ads.push('')
}

// 删除路线
const deleteObject = (index) => {
	if (customRouteForm.value.ads.length > 1) {
		customRouteForm.value.ads.splice(index, 1)
	} else {
		proxy.$message({
			message: '至少选择一个路线',
			type: 'warning'
		})
	}
}

const paymentMethods = ref([])
// 初始化分组数据结构
const groupedData = ref([
	{ type: 1, title: '门店自取', list: [] },
	{ type: 2, title: '物流配送', list: [] },
	{ type: 3, title: '自建配送', list: [] }
])
const getSfeeLs = async () => {
	try {
		let res = await proxy.$api({ url: config.company_sfee_ls, data: {} })
		let result = res.data
		if (res.status == 1 && result) {
			groupedData.value.forEach(group => {
				group.list = []
			})
			const dataList = result.ls || result
			dataList.forEach(item => {
				const targetGroup = groupedData.value.find(group => group.type === Number(item.type))
				if (targetGroup) {
					targetGroup.list.push(item) // 修复：直接使用找到的目标分组添加数据
				}
			})
			paymentMethods.value = groupedData.value
		}
	} catch (error) { }
}
getSfeeLs()

// 获取省市区
const getdistrictsData = async () => {
	let param = {};
	let url = config.COMM_DISTRICTS;
	let res = await proxy.$api({ url: url, data: param });
	if (!res) return;
	if (res.status == 1 && res.data) {
		optionsPosition.value = res.data;
	}
}
getdistrictsData()

// area: "", // 632724
// city: "", // 632700
// province: "", // 630000
// title: "" // 青海省玉树藏族自治州治多县

// 选择省市区
const handleChange = (i, e) => {
	let district = getmapNameFun(e);
	customRouteForm.value.dist[i].province = e[0]; // 省
	customRouteForm.value.dist[i].city = e[1]; // 市
	customRouteForm.value.dist[i].area = e[2]; // 区
	customRouteForm.value.dist[i].title = district; // 省市区
	console.log("customRouteForm.value.dist===",customRouteForm.value.dist)
}
// 自建配送  [
// ['province'=>'','city'=> '','area'=> '','title'=> '',],
// ['province'=>'','city'=> '','area'=> '','title'=> '',],
// ['province'=>'','city'=> '','area'=> '','title'=> '',],
// ]

// 获取地址名称
const getmapNameFun = (arr) => {
	let name = "";
	const province = arr[0] | "";
	const city = arr[1] | "";
	const area = arr[2] | "";
	if (province) {
		optionsPosition.value.map((v) => {
			if (province == v.code) {
				name += v.name;
				if (city) {
					v.cityList.map((vs) => {
						if (city == vs.code) {
							name += vs.name;
							if (area) {
								vs.cityList.map((vw) => {
									if (area == vw.code) {
										name += vw.name;
									}
								});
							}
						}
					});
				}
			}
		});
	}
	return name;
}

// 编辑弹窗相关
const dialogVisible = ref(false)
const editForm = ref({ title: '', id: 0, status: 1 })

// 切换收款方式选择状态
const togglePaymentMethod = async (paraIndex, index) => {
	paymentMethods.value[paraIndex].list[index].status = paymentMethods.value[paraIndex].list[index].status == 1 ? 2 : 1;
}

const savePaymentHandle = async () => {
	let params = {
		ids: paymentMethods.value.flatMap(group =>
			group.list
				.filter(item => item.status == 1)
				.map(item => item.id)
		).filter(id => id != null),
		ch: 'status',
	}
	try {
		let res = await proxy.$api({ url: config.company_sfee_saves, data: params })
		if (res.status == 1) {
			proxy.$message({
				message: '保存成功',
				type: 'success'
			})
		}
		getSfeeLs()
	} catch (error) { }
}

const addCustomPayment = () => {
	dialogVisible.value = true
	editForm.value = { title: '', id: 0, status: 1 }
}

const addCustomRoute = () => {
	boxVisible.value = true
	customRouteForm.value = {
		ads: [""],
		dist: [
			{
				province: "", // 630000
				city: "", // 632700
				area: "", // 632724
				title: "", // 青海省玉树藏族自治州治多县
				codeArr: [],
			},
		],
		id: "0",
		title: "",
		txt: "",
		type: "3",
		status: "1",
	}
}


// luxian // 路线
// kuaidi // 快递
// hdfk // 货到付款
// qita // 其他
// myf // 免运费
// mendian // 门店
const getMethodIcon = (name) => {
	let txt = 'qita'
	if (name.includes('路')) {
		txt = 'luxian'
	}
	if (name.includes('快')) {
		txt = 'kuaidi'
	}
	if (name.includes('到付', '货到付款')) {
		txt = 'hdfk'
	}
	if (name.includes('免')) {
		txt = 'myf'
	}
	if (name.includes('店')) {
		txt = 'mendian'
	}
	return txt
}

const editPaymentMethod = async (item) => {
	if (item.type == 2) {
		editForm.value = { ...item }
		dialogVisible.value = true
	} else if (item.type == 3) {
		let params = {
			id: item.id
		}
		let res = await proxy.$api({ url: config.company_sfee_info, data: params })
		let result = res.data
		if (res.status == 1) {
			// 确保 optionsPosition 数据已经加载完成
			if (!optionsPosition.value || optionsPosition.value.length === 0) {
				await getdistrictsData()
			}
			
			customRouteForm.value = result
			// 关键修复：将 codeArr 中的数字类型转为字符串类型
			customRouteForm.value.dist = result.dist.map(item => ({
				...item,
				// 确保 codeArr 中的所有值都是字符串类型
				codeArr: [
					String(item.province), 
					String(item.city), 
					String(item.area)
				]
			}))
			delete customRouteForm.value.fee
			console.log("customRouteForm.value===", customRouteForm.value)
			// 在下一个渲染周期后打开弹窗，确保数据绑定完成
		setTimeout(() => {
				boxVisible.value = true
			}, 100)
		}
	}
}

const confirmEdit = () => {
	if (editForm.value.title && editForm.value.title.trim()) {
		savePaymentSettings()
	} else {
		proxy.$message.error('请输入名称')
	}
}

const handleClose = () => {
	boxVisible.value = false
	dialogVisible.value = false
}

const deletePaymentMethod = async (item) => {
	try {
		let res = await proxy.$api({ url: config.company_sfee_del, data: { id: item?.id } })
		if (res.status == 1) {
			getSfeeLs()
		} else {
			proxy.$message.error(res?.msg || '删除失败')
		}
	} catch (error) { }
}

const savePaymentSettings = async () => {
	let params = {
		...editForm.value
	}
	try {
		let res = await proxy.$api({ url: config.company_sfee_save, data: params })
		if (res.status == 1) {
			dialogVisible.value = false
			getSfeeLs()
		}
	} catch (error) { }
}

onMounted(() => { })


</script>

<style lang="scss" scoped>
.payment-method-container {
	height: 100%;
	display: flex;
	flex-direction: column;
	background-color: #f5f7fa;
}

.content-section {
	flex: 1;
	padding: 16px 20px;
	overflow-y: auto;
	border-radius: 12px;
}

.payment-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.payment-info {
	display: flex;
	flex-direction: column;
	gap: 2px;
}

.payment-name {
	font-size: 16px;
	font-weight: 600;
	color: white;
}

.payment-status {
	font-size: 13px;
	color: rgba(255, 255, 255, 0.9);
	opacity: 0.9;
}

/* 区域标题 */
.section-title {
	font-size: 15px;
	font-weight: 600;
	color: #303133;
	margin-bottom: 12px;
	padding-left: 6px;
	border-left: 3px solid #4096ff;
}

.payment-methods-card {
	overflow: hidden;
	padding: 10px;
}

.payment-methods-cell {
	width: 100%;
	background-color: white;
	padding: 14px 28px;
	border-bottom: 1px solid #f0f2f5;
	transition: background-color 0.2s ease;

	&:hover:not(.payment-disabled) {
		background-color: #f8f9ff;
	}
}

.payment-method-item {
	border-radius: 0;

	&:last-child {
		border-bottom: none;
	}

	&:first-child .payment-methods-cell {
		border-top-left-radius: 8px;
		border-top-right-radius: 8px;
	}

	&:last-child .payment-methods-cell {
		border-bottom-left-radius: 8px;
		border-bottom-right-radius: 8px;
	}
}

.payment-disabled {
	opacity: 0.6;
	cursor: not-allowed;
}

.method-info {
	display: flex;
	align-items: center;
	gap: 12px;
	cursor: pointer;
	flex: 1;
}

.method-icon {
	height: 32px;
	width: 32px;
}

.method-name {
	font-size: 18px;
	font-weight: 500;
	color: #303133;
}

/* 支付操作区域 */
.payment-actions {
	display: flex;
	align-items: center;
	gap: 12px;
}

/* 自定义复选框 */
.custom-checkbox {
	width: 24px;
	height: 24px;
	border: 2px solid #dcdfe6;
	border-radius: 4px;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	transition: all 0.2s ease;
	background-color: white;

	&.checkbox-checked {
		background-color: #4096ff;
		border-color: #4096ff;
		color: white;
	}

	&.checkbox-disabled {
		cursor: not-allowed;
	}
}

/* 操作按钮区域 */
.action-buttons {
	display: flex;
	align-items: center;
	gap: 4px;
}

.edit-btn {
	color: #67c23a;
	padding: 0 8px;
	font-size: 20px;
}

.delete-btn {
	color: #f56c6c;
	padding: 0 8px;
	font-size: 20px;
}

/* 添加自定义收款方式 */
.add-custom-section {
	text-align: center;
	margin-top: 8px;
}

.add-button {
	font-size: 14px;
	color: #4096ff;
	padding: 8px 16px;
	border-radius: 6px;
	background-color: #ecf5ff;
	transition: all 0.2s ease;

	&:hover {
		background-color: #4096ff;
		color: white;
		transform: translateY(-1px);
	}

	i {
		margin-right: 4px;
	}
}

.object-box {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
	flex-direction: row;
	gap: 10px;
	border: 1px solid #f1f1f1;
	border-radius: 10px;
	padding: 10px;

	.object-item {
		box-sizing: border-box;
		height: 50px;
		width: 360px;
		padding: 10px;
		border: 1px solid #DCDFE6;
		border-radius: 5px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		gap: 10px;
		position: relative;

		.object-item-name-box {
			display: flex;
			align-items: center;
			flex-direction: row;
			margin-left: 5px;
			flex: 1;

			div {
				font-size: 12px;
				color: #666;
			}

			.object-item-name {
				flex: 1;
			}
		}

		.object-item-delete-box {
			position: absolute;
			right: 0;
			top: 0;
			cursor: pointer;
			width: 20px;
			height: 20px;
			background-color: rgba(0, 0, 0, 0.1);
			border-bottom-left-radius: 6px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #FFFFFF;
			font-size: 12px;

			&:hover {
				background: rgba(0, 0, 0, 0.3);
			}
		}

	}
}


/* 底部保存按钮 */
.footer-section {
	padding: 16px 20px;
	background-color: white;
	box-shadow: 0 -1px 6px rgba(0, 0, 0, 0.02);
}

.save-button {
	width: 100%;
	padding: 12px;
	font-size: 15px;
	font-weight: 600;
	border-radius: 8px;
	background: linear-gradient(135deg, #4096ff 0%, #69b1ff 100%);
	border: none;
	color: white;
	transition: all 0.2s ease;
	box-shadow: 0 2px 6px rgba(64, 150, 255, 0.2);

	&:hover {
		background: linear-gradient(135deg, #3a8ee6 0%, #5da9ff 100%);
		transform: translateY(-1px);
		box-shadow: 0 4px 10px rgba(64, 150, 255, 0.3);
	}

	&:active {
		transform: translateY(0);
		box-shadow: 0 2px 4px rgba(64, 150, 255, 0.2);
	}
}
</style>